package com.test.shiro.handler;

import com.test.shiro.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/9/8 16:18
 */
@Controller
@RequestMapping(path = "/shiro")
public class ShiroHandler {
    private final static Logger log = LoggerFactory.getLogger(ShiroHandler.class);

    @Autowired
    private ShiroService shiroService;

    @RequestMapping("/testShiroAnnocation")
    public String testShiroAnnotation(HttpSession session) {
        session.setAttribute("key", "value:123456");
        shiroService.testService();
        return "redirect:/list.jsp";
    }

    @RequestMapping(path = "/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        // 获取当前的Subject,调用SecurityUtils.getSubject（）
        Subject currentUser = SecurityUtils.getSubject();

        // 测试当前的用户是否已经被认证，即是否已经登录
        if (!currentUser.isAuthenticated()) {
            // 把用户名和密码封装为UsernamePasswordToken对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // RememberMe
            token.setRememberMe(true);
            try {
                // 调用subject的login，执行登录
                currentUser.login(token);
                // 若没有指定的账户，shiro会抛出UnknownAccountException
            } catch (AuthenticationException ae) {
                // 所有认证异常的父类
                //unexpected condition?  error?
                log.info("登陆失败！" + ae.getMessage());
            }
        }

        return "redirect:/list.jsp";
    }
}
